// Copyright (c) 2024 Deng Zicheng
// "CarController" is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import prompt from '@system.prompt';
import Router from '@system.router';
import {MessageData} from "../blueTooth/blueTooth"
import BLE from "../blueTooth/blueTooth"

const ABILITY_TYPE_EXTERNAL = 0;
const ACTION_SYNC = 0;
const ACTION_MESSAGE_CODE_SUBSCRIBE_AUTO = 1003;
const ACTION_MESSAGE_CODE_UNSUBSCRIBE_AUTO = 1004;

export default {
    data: {
        connect_state:null,
        barrier:false,
        speed:0,
        direction:90,
        RSSI:0,
        map:{
            mapBaseSize:25,
            proportion:1,//比例
            x:0,//地图坐标
            y:0,
            touch_x:0,//触模点坐标缓存
            touch_y:0,
            car_x:0,//小车坐标
            car_y:0,
            begin_x_origin:285,//小车坐标初始点
            begin_y_origin:238,
            self_drive_state:false,//自动控制状态标志位
            destination:{
                click_state:false,//双击等待标志位
                state:false,//目的地设置状态标志位
                x:0,//目的地坐标
                y:0,
            },
            distance:{//距离数据
                x:0,
                y:0
            },
            motion:{//上次移动距离
                x:0,
                y:0,
            },
            last_x:0,
            last_y:0,
            tracks:[]
        }
    },
    onInit() {
        this.init();
    },
    init(){
        this.map.last_x=this.map.begin_x_origin;
        this.map.last_y=this.map.begin_y_origin;
        this.map.car_x=this.map.begin_x_origin;
        this.map.car_y=this.map.begin_y_origin;
        this.map.destination.state=false;
        this.map.distance.x=0;
        this.map.distance.y=0;
        this.map.tracks=[];
        this.map.x=0;
        this.map.y=0;
    },
    onShow(){
        this.actionJava("subscribe");
    },
    onDestroy(){
        this.actionJava("unsubscribe");
    },
    //移动地图
    move_map(e){
        //计算移动差值
        let diff_x=e.touches[0].localX-this.map.touch_x;
        let diff_y=e.touches[0].localY-this.map.touch_y;
        //更新地图位置
        this.map.x+=diff_x;
        this.map.y+=diff_y;
        //更新起点标志
        this.map.car_x+=diff_x;
        this.map.car_y+=diff_y;
        //更新目的地标志
        this.map.destination.x+=diff_x;
        this.map.destination.y+=diff_y;
        //更新上次坐标
        this.map.last_x+=diff_x;
        this.map.last_y+=diff_y;
        //更新轨迹
        for(let i=0;i<this.map.tracks.length; i++){
            this.map.tracks[i].x+=diff_x;
            this.map.tracks[i].y+=diff_y;
        }
        //更新滑动参考标志
        this.map.touch_x=e.touches[0].localX;
        this.map.touch_y=e.touches[0].localY;
    },

    //连击灵敏度控制函数
    change_click_state(){
        this.map.destination.click_state=false;
    },
    //开始移动地图和双击设置目的地
    startTouch_map(e){
        //判断双击事件
        if (this.map.destination.click_state==true) {
            if (this.notice_driving()) {
                return;
            }
            let diff_x=Math.abs(this.map.touch_x-e.touches[0].localX);
            let diff_y=Math.abs(this.map.touch_y-e.touches[0].localY);
            if(diff_x<10&&diff_y<10){
                this.set_destination(e.touches[0].localX-26,e.touches[0].localY-50);
            }
        }
        if (this.map.destination.click_state==false){
            this.map.destination.click_state=true;
            setTimeout(this.change_click_state,300)
        }
        //初始化滑动参考标志
        this.map.touch_x=e.touches[0].localX;
        this.map.touch_y=e.touches[0].localY;
    },
    //设置目的地
    set_destination(x,y){
        this.map.destination.x=x;
        this.map.destination.y=y;
        this.map.destination.state=true;
        this.compute_distance();
    },
    //计算相对位置
    compute_distance(){
        if(this.map.destination.state==true){
            this.map.distance.x=Math.round(-(this.map.car_x-this.map.destination.x)/this.map.mapBaseSize*this.map.proportion*10)/10
            this.map.distance.y=Math.round((this.map.car_y-this.map.destination.y-23)/this.map.mapBaseSize*this.map.proportion*10)/10;
        }else{
            this.map.distance.x=0;
            this.map.distance.y=0;
        }
    },

    //重置目的地
    reset_destination(){
        if (this.notice_driving()) {
            return;
        }
        this.map.tracks=[];
        this.map.destination.state=false;
        this.map.distance.x=0;
        this.map.distance.y=0;
    },
    //比例尺改变
    change_proportion(){
        if (this.notice_driving()) {
            return;
        }
        if(this.map.proportion==1){
            this.map.proportion=5;
        }else {
            this.map.proportion=1;
        }
        if(this.map.destination.state==true){
            this.compute_distance();
        }
    },
    //定位出发点
    back_car_point(){
        let diff_x=this.map.car_x-this.map.begin_x_origin;
        let diff_y=this.map.car_y-this.map.begin_y_origin;
        this.map.car_x=this.map.begin_x_origin;
        this.map.car_y=this.map.begin_y_origin;
        this.map.destination.x-= diff_x;
        this.map.destination.y-= diff_y;
        this.map.x-=diff_x;
        this.map.y-=diff_y;
        this.map.last_x-=diff_x;
        this.map.last_y-=diff_y;
        for(let i=0;i<this.map.tracks.length; i++){
            this.map.tracks[i].x-=diff_x;
            this.map.tracks[i].y-=diff_y;
        }
    },
    //自动行驶提醒
    notice_driving(){
        if (this.map.self_drive_state == true) {
            prompt.showDialog({message:"自动行进中该操作不可用！"});
            return true;
        }
        return false;
    },
    //自动行驶控制
    self_drive(){
        if (this.map.destination.state==false) {
            prompt.showDialog({message:"未设置目的地！"});
            return;
        }
        this.map.self_drive_state=!this.map.self_drive_state;
        if(this.map.self_drive_state==true){
            //开始自动行驶操作

            let data=new MessageData();
            data.option="begin_auto";
            data.destination_X=Math.round(this.map.distance.x*10);
            data.destination_Y=Math.round(this.map.distance.y*10);
            BLE.actionJava(data);
        }else {
            this.map.motion.x=0;
            this.map.motion.y=0;
            //停止自动行驶操作
            let data=new MessageData();
            data.option="stop";
            BLE.actionJava(data);
        }
    },
    //更新图标
    updateLocation(x,y){
        //获取移动偏差
        let diff_x=x/this.map.proportion*this.map.mapBaseSize;
        let diff_y=y/this.map.proportion*this.map.mapBaseSize;

        //地图
        this.map.x-=(diff_x-this.map.motion.x);
        this.map.y+=(diff_y-this.map.motion.y);
        //目标点
        this.map.destination.x-=(diff_x-this.map.motion.x);
        this.map.destination.y+=(diff_y-this.map.motion.y);
        //上次相对位置
        this.map.last_x-=(diff_x-this.map.motion.x);
        this.map.last_y+=(diff_y-this.map.motion.y);
        //轨迹
        for(let i=0;i<this.map.tracks.length; i++){
            this.map.tracks[i].x-=(diff_x-this.map.motion.x);
            this.map.tracks[i].y+=(diff_y-this.map.motion.y);
        }
        console.info((diff_x-this.map.motion.x));
        //计算上次位置相对距离
        let distance=Math.abs(Math.pow(this.map.car_x-this.map.last_x,2)+Math.pow(this.map.car_y-this.map.last_y,2));
        if(distance>0.1){//更新轨迹
            this.map.tracks.push({x:this.map.last_x,y:this.map.last_y});
            if(this.map.tracks.length>100){
                this.map.tracks.shift();
            }
            this.map.last_x=this.map.car_x;
            this.map.last_y=this.map.car_y;
        }
        this.map.motion.x=diff_x;
        this.map.motion.y=diff_y;
        this.compute_distance();
        if(this.map.self_drive_state){
            distance=Math.pow(this.map.distance.x,2)+Math.pow(this.map.distance.y,2);
            if(distance<0.1){
                this.map.self_drive_state=false;
                prompt.showDialog({message:"已到达!"});
                //停止自动控制
                let data=new MessageData();
                data.option="stop";
                BLE.actionJava(data);
                this.init();
            }
        }
    },
    blue_page(){
        Router.push({
            uri:"pages/blueTooth/blueTooth",
        })
    },
    //控制信号发送
    car_control(){
        if (this.connect_state) {
            let data=new MessageData();
            BLE.actionJava(data);
        }
    },
    /**
     * action初始化
     * @returns
     */
    initAction(){
        var action = {};
        action.bundleName = 'com.sinan.myapplication';
        action.abilityName = 'com.sinan.myapplication.bleBTServiceAbility';
        return action;
    },
    /**
     * 订阅相关功能初始化
     * @param method
     * @returns
     */
    initActionSubscribe(method){
        var action=this.initAction();
        if (method == "subscribe") {
            action.messageCode = ACTION_MESSAGE_CODE_SUBSCRIBE_AUTO;
        }else if(method == "unsubscribe"){
            action.messageCode = ACTION_MESSAGE_CODE_UNSUBSCRIBE_AUTO;
        }
        action.abilityType = ABILITY_TYPE_EXTERNAL;
        action.syncOption = ACTION_SYNC;
        return action;
    },
    /**
     * 调用java实现
     * @param method
     * @param option=''
     */
    async actionJava(method) {
        if(method=="subscribe"){
            var result = await FeatureAbility.subscribeAbilityEvent(this.initActionSubscribe(method),this.notifyHandle);
            var ret = JSON.parse(result);
            if (ret.code == 0) {
                console.info('subscribe success, result:' + result);
            } else {
                console.error('subscribe error, result:' + result);
            }
        }else if(method=="unsubscribe"){
            var result = await FeatureAbility.unsubscribeAbilityEvent(this.initActionSubscribe(method));
            var ret = JSON.parse(result);
            if (ret.code == 0) {
                console.info('unsubscribe success, result: ' + result);
            } else {
                console.error('unsubscribe error, result: ' + result);
            }
        }
    },


    /**
     * javaPA通知处理
     * @param callbackData
     */
    notifyHandle(callbackData){
        var callbackJson = JSON.parse(callbackData).data;
        console.info('eventData is: ' + JSON.stringify(callbackJson));
        if(callbackJson.type=="connection"){
            if (callbackJson.num1 == 1) {
                this.connect_state=true;
            }else {
                this.connect_state=false;
            }
        }else if (callbackJson.type=="S_S"){
            this.speed=callbackJson.num3;
            let value=callbackJson.num1;
            if (value==1) {
                this.barrier=true;
            }else {
                this.barrier=false;
            }
        }else if (callbackJson.type=="S_LD"){
            if(this.map.self_drive_state==true){
                this.updateLocation(callbackJson.num3,callbackJson.num4);
            }
            this.direction=callbackJson.num1+90;
        }else if(callbackJson.type=="RSSI"){
            this.RSSI=callbackJson.num1;
        }
    }
}
